package com.example.nkj.grid;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;


public class grid extends AppCompatActivity
{
    /* Called when the activity is first created. */
    //定义图片整型数组
    private int[] mImages={
            R.drawable.png1,
            R.drawable.png2,
            R.drawable.png3,
            R.drawable.png4,
            R.drawable.png5,
            R.drawable.png6,
            R.drawable.png7,
            R.drawable.png8,
            R.drawable.png9

    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid);

        //实例化GridView
        GridView mGridView=(GridView) findViewById(R.id.gridview);
        // 生成动态数组，并且传入数据
        ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();

        for(int i = 0; i < 9; i++)
        {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("ItemImage", mImages[i]);// 添加图像资源的ID
            map.put("ItemText", "NO." + String.valueOf(i+1));// 按序号做ItemText
            lstImageItem.add(map);
        }
        //构建一个适配器
        SimpleAdapter simple = new SimpleAdapter(this, lstImageItem, R.layout.gridviewitem, new String[] { "ItemImage", "ItemText" }, new int[] {R.id.ItemImage, R.id.ItemText });
        mGridView.setAdapter(simple);
        //添加选择项监听事件
        mGridView.setOnItemClickListener(new GridView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                Toast toast=Toast.makeText(getApplicationContext(), "你选择了"+(position+1)+"号图片", 1);
                toast.setGravity(Gravity.BOTTOM, 0, 0);
                toast.show();
            }
        });

    }
}
